package com.umeox.watch.prayertime.ui

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.provider.Settings
import android.text.format.DateFormat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.umeox.moto.common.log.Logger
import com.umeox.moto.watch.themes.app.ThemeAppCompatActivity
import com.umeox.watch.moto.dataservice.constants.Constants
import com.umeox.watch.prayertime.R
import com.umeox.watch.prayertime.adapter.PrayerTimeListAdapter
import com.umeox.watch.prayertime.base.BaseApp
import com.umeox.watch.prayertime.bean.PrayerTimeInfo
import com.umeox.watch.prayertime.utils.PrayerTimesCoordinator
import java.util.*

class PrayerTimeListActivity : ThemeAppCompatActivity() {

    private lateinit var prayerTimeList: MutableList<PrayerTimeInfo>

    private lateinit var  prayerTimeListAdapter : PrayerTimeListAdapter

    private var is24HourFormat: Boolean = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_prayer_time_list)
        is24HourFormat = DateFormat.is24HourFormat(this)
        //获取本地经纬度
        val lat: String? = Settings.Global.getString(contentResolver, "LAT")
        val long: String? = Settings.Global.getString(contentResolver, "LONG")
        Logger.e("lat=$lat,long=$long")
        if ((!lat.isNullOrEmpty() && lat != "-999") && (!long.isNullOrEmpty() && long != "-999")) {
            calcPrayerTime(lat.toDouble(), long.toDouble())
        }
        val prePrayerTimeIndex: Int =
            binarySearchRight(prayerTimeList, System.currentTimeMillis())
        Logger.e("$prayerTimeList")
        Logger.e("prePrayerTimeIndex=$prePrayerTimeIndex")

        if (prePrayerTimeIndex != -1) { //等于-1 说明当前时间是午夜后半夜，列表不需要高亮某个时刻
            prayerTimeList[prePrayerTimeIndex].isHighLight = true
        }
        Logger.e("$prayerTimeList")


        val timesRv: RecyclerView = findViewById(R.id.rv_times)
        prayerTimeListAdapter = PrayerTimeListAdapter(prayerTimeList,is24HourFormat)
        timesRv.adapter = prayerTimeListAdapter
        timesRv.setHasFixedSize(true)
        timesRv.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
        //timesRv.setItemViewCacheSize(7)
        timesRv.recycledViewPool.setMaxRecycledViews(0,0)

        registerPrayerSettingChangeReceiver()
    }

    private fun registerPrayerSettingChangeReceiver() {
        val mFilter = IntentFilter()
        mFilter.addAction(Constants.ACTION_UPDATED_PRAYER_TIME)
        registerReceiver(mPrayerSettingChangeReceiver, mFilter)
    }


    private val mPrayerSettingChangeReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            Logger.e("action=$action")
           if (action == Constants.ACTION_UPDATED_PRAYER_TIME) {  //祈祷设置发生改变，重新计算
               val lat: String? = Settings.Global.getString(contentResolver, "LAT")
               val long: String? = Settings.Global.getString(contentResolver, "LONG")
               Logger.e("lat=$lat,long=$long")
               if ((!lat.isNullOrEmpty() && lat != "-999") && (!long.isNullOrEmpty() && long != "-999")) {
                    calcPrayerTime(lat.toDouble(), long.toDouble())
                    val prePrayerTimeIndex: Int =
                        binarySearchRight(prayerTimeList, System.currentTimeMillis())

                    Logger.e("prePrayerTimeIndex=$prePrayerTimeIndex")

                    if (prePrayerTimeIndex != -1) { //等于-1 说明当前时间是午夜后半夜，列表不需要高亮某个时刻
                        prayerTimeList[prePrayerTimeIndex].isHighLight = true
                    }
                    Logger.e("$prayerTimeList")
                    //更新列表
                    prayerTimeListAdapter.setData(prayerTimeList)
                }
            }
        }
    }

    private fun calcPrayerTime(lat: Double, long: Double) {
        val prayerTimesCoordinator = PrayerTimesCoordinator()
        prayerTimesCoordinator.updateParameters(DateFormat.is24HourFormat(this))
        val timeZone: TimeZone = TimeZone.getDefault()
        val time = timeZone.rawOffset //获取时差，返回值毫秒
        prayerTimeList = prayerTimesCoordinator.getPrayerTimeData(
            lat,
            long,
            (time / 1000 / 60 / 60).toDouble()
        )

        prayerTimeList.removeAt(prayerTimeList.size - 1)
    }


    //找到<=target最右的位置
    private fun binarySearchRight(arr: MutableList<PrayerTimeInfo>, target: Long): Int {
        var left = 0
        var right = arr.size - 1
        var result = -1
        while (left <= right) {
            val middle = left + (right - left shr 1)
            if (arr[middle].timestamp <= target) {
                result = middle
                left = middle + 1
            } else {
                right = middle - 1
            }
        }
        return result
    }

    override fun onDestroy() {
        super.onDestroy()
        try {
            unregisterReceiver(mPrayerSettingChangeReceiver)
        } catch (ignored: Exception) {

        }
    }
}